package com.xinan.utils;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import sun.misc.BASE64Decoder;


/**
 * 功能: 该类目前只使用到界面层 时间: 2012-10-11 11:54:15
 *
 * @author <a>wzz</a>
 * @version 1.0
 */

public final class CommonUtil {
    private static Logger log = Logger.getLogger(CommonUtil.class);

    private static Properties Props;

    /**
     * 将给定日期加指定天数返回
     *
     * @param date
     *            日期字符串
     * @param rd
     *            添加天数
     * @return Date 返回加rd天后的日期
     */
    public static java.util.Date addDay(java.util.Date date, int rd) {
        if (date == null)
            return null;
        try {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(GregorianCalendar.DATE, rd);
            date = calendar.getTime();
            return date;
        } catch (Exception pe) {
            log.error(pe.getMessage());
        }
        return null;
    }

    /**
     * 将给定日期加指定天数返回
     *
     * @param date
     *            日期字符串
     * @param rd
     *            添加天数
     * @param lx
     * @return Date 返回加rd天后的日期
     */
    public static java.util.Date addDay(java.util.Date date, String lx, int rd) {
        if (date == null)
            return null;
        try {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            if (lx.toLowerCase().equals("year")) {
                calendar.add(GregorianCalendar.YEAR, rd);
            } else if (lx.toLowerCase().equals("month")) {
                calendar.add(GregorianCalendar.MONTH, rd);
            } else if (lx.toLowerCase().equals("date")) {
                calendar.add(GregorianCalendar.DATE, rd);
            }
            date = calendar.getTime();
            return date;
        } catch (Exception pe) {
            log.error(pe.getMessage());
        }
        return null;
    }

    /**
     * 将日期字符串加指定天数转换为日期返回
     *
     * @param strDate
     *            日期字符串
     * @param rd
     *            添加天数
     * @param lx
     * @return Date 返回加rd天后的日期
     */
    public static java.util.Date addDay(String strDate, String lx, int rd) {
        if (strDate == null)
            return null;
        try {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(
                    "yyyy-MM-dd");
            java.util.Date date = formatter.parse(strDate);
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            if (lx.toLowerCase().equals("year")) {
                calendar.add(GregorianCalendar.YEAR, rd);
            } else if (lx.toLowerCase().equals("month")) {
                calendar.add(GregorianCalendar.MONTH, rd);
            } else if (lx.toLowerCase().equals("date")) {
                calendar.add(GregorianCalendar.DATE, rd);
            }
            date = calendar.getTime();
            return date;
        } catch (ParseException pe) {
            log.error(pe.getMessage());
        }
        return null;
    }

    /**
     * 在字符前或后加指定字符到指定长度
     *
     * @param str
     *            待处理字符串
     * @param s
     *            指定添加字符
     * @param ic
     *            指定长度
     * @param before
     *            是否在前面添加
     * @return String 补足位数的字符串
     */
    public static String addStr(String str, String s, int ic, boolean before) {
        if (str == null)
            str = "";
        while (str.length() < ic) {
            if (before)
                str = s + str;
            else
                str = str + s;
        }
        return str;
    }

    /**
     * 把字符数组按给定字符串连接成新字符串
     *
     * @param str
     *            要转换的字符数组
     * @param jstr
     *            连接字符串
     * @return String 返回连接后的新字符串
     */
    public static String arrayToString(String[] str, String jstr) {
        if (str == null)
            return null;
        String retStr = null;
        for (int i = 0; i < str.length; i++) {
            if (retStr == null) {
                retStr = str[i];
            } else {
                retStr = retStr + jstr + str[i];
            }
        }
        return retStr;
    }

    /**
     * 根据role中的规则进行计算 role中的元素为map， map的key： c1:第一操作数的key c2:第二操作数的key
     * opereator：运算符（+,-,*,/） r:计算结果的key
     *
     * @param map
     * @param role
     * @return 计算后的列表
     */
    public static Map calculate(Map map, List role) {
        Iterator iterator = role.iterator();
        Map tmp;
        Object c1, c2, operator;
        while (iterator.hasNext()) {
            tmp = (Map) iterator.next();
            c1 = map.get(tmp.get("c1"));
            c2 = map.get(tmp.get("c2"));
            operator = tmp.get("operator");
            if ((c1 == null || c1.equals("null"))
                    && (c2 == null || c2.equals("null"))) {
                continue;
            }
            if (c1 == null || c1.equals("null")) {
                c1 = new BigDecimal(0);
            }
            if ((c2 == null || c2.equals("null")) && !operator.equals("/")) {
                c2 = new BigDecimal(0);
            }
            if (c1 instanceof BigDecimal && c2 instanceof BigDecimal) {
                if (operator.equals("+")) {
                    map.put(tmp.get("r"), ((BigDecimal) c1)
                            .add((BigDecimal) c2));
                } else if (operator.equals("-")) {
                    map.put(tmp.get("r"), ((BigDecimal) c1)
                            .subtract((BigDecimal) c2));
                } else if (operator.equals("*")) {
                    map.put(tmp.get("r"), ((BigDecimal) c1)
                            .multiply((BigDecimal) c2));
                } else if (operator.equals("/")) {
                    map.put(tmp.get("r"), ((BigDecimal) c1).divide(
                            ((BigDecimal) c2), 2, BigDecimal.ROUND_HALF_EVEN));
                }
            }
        }
        return map;
    }

    /**
     * 润年检测
     *
     * @param year1
     *            年份
     * @return boolean 是返回真
     */
    public static boolean checkLeapYear(String year1) {
        if (year1 == null)
            return false;
        int year = Integer.parseInt(year1);
        if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
            return true;
        }
        return false;
    }

    /**
     * ===================================字符串处理结束===============//
     * ================================字符串编码转换开始===============// 字符串编码转换为GBK
     *
     * @param str
     *            被处理的字符串
     * @return String 将数据库中读出的数据进行转换
     */
    public static String convert(String str) {
        return str;
		/*
		 * String str1 = ""; if (str != null) { try { str1 = new
		 * String(str.getBytes("ISO8859_1"), "GBK"); } catch (Exception e) {
		 * str1 = ""; } } return str1;
		 */
    }

    /**
     * 以format格式格式化日期date
     *
     * @param date
     * @param format
     * @return 格式化的日期
     */
    public static String formatDate(Date date, String format) {
        if (date == null) {
            return "";
        }
        if (format == null || format.trim().equals("")) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 以"yyyy-MM-dd"格式格式化日期
     *
     * @param date
     * @return 格式化的日期
     */
    public static String formatDateTwo(Date date) {
        return formatDate(date, "yyyy-MM-dd");
    }

    /**
     * 字符串格式转换输出 指定输出字符串输出的长度，当要输出的字符串超过制定的长度时会自动截取在后边加"..."代替过长的字符
     *
     * @param str
     * @param len
     * @return 格式化后的字符串
     */
    public static String formatStr(String str, int len) {
        if (str == null)
            return str;
        int strLen = str.length();
        if (strLen <= len) {
            return str;
        }
        return str.substring(0, len) + "...";
    }

    /**
     * 去除str中的所有HTML代码
     *
     * @param str
     * @return str中的非HTML代码部分
     */
    public static String getAbStract(String str) {
        String regexpForHtml = "<([^>]*)>";
        str = str.replaceAll(regexpForHtml, "");
        str = str.replaceAll("<", "");
        str = str.replaceAll(">", "");
        return str;
    }

    /**
     * 将字符串转换为BASE64编码格式
     *
     * @param str
     *            字符串
     * @return String 返回处理后的字符串
     */
    public static String getBASE64(String str) {
        if (str == null)
            return null;
        try {
            return (new sun.misc.BASE64Encoder()).encode(str.getBytes("GBK"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ============================字符串编码转换结束=================//
     * =============================日期处理==========================//
     * 取得当前日期的10位字符串格式(yyyy-mm-dd)
     *
     * @return String 返回当前年月日
     */
    public static String getCurrentDate() {
        Calendar c = Calendar.getInstance();
        int y = c.get(Calendar.YEAR);
        int m = c.get(Calendar.MONTH) + 1;
        int d = c.get(Calendar.DAY_OF_MONTH);
        String s = String.valueOf(y) + "-"
                + addStr(String.valueOf(m), "0", 2, true) + "-"
                + addStr(String.valueOf(d), "0", 2, true);
        return s;
    }

    public static String getCurrentDateTime() {
        Calendar c = Calendar.getInstance();
        int y = c.get(Calendar.YEAR);
        int m = c.get(Calendar.MONTH) + 1;
        int d = c.get(Calendar.DAY_OF_MONTH);
        int h = c.get(Calendar.HOUR_OF_DAY);
        int mi = c.get(Calendar.MINUTE);
        int ss = c.get(Calendar.SECOND);
        int mss = c.get(Calendar.MILLISECOND);

        String s = "" + addStr(String.valueOf(y), "0", 4, true) +
                addStr(String.valueOf(m), "0", 2, true) +
                addStr(String.valueOf(d), "0", 2, true) +
                addStr(String.valueOf(h), "0", 2, true) +
                addStr(String.valueOf(mi), "0", 2, true) +
                addStr(String.valueOf(ss), "0", 2, true) +
                addStr(String.valueOf(mss), "0", 3, true);
        return s;
    }

    /**
     * 自定义时间显示方式
     *
     * @param type
     *            类型<br>
     *            1 : yyyy-mm-dd<br>
     *            2 : yyyy-mm-dd hh:mm:ss<br>
     *            3 : yyyy年mm月dd日
     * @param date
     *            日期
     * @return String <br>
     *         1: 返回yyyy-mm-dd<br>
     *         2: 返回yyyy-mm-dd hh:mm:ss<br>
     *         3: XXXX年XX月XX日 4: XX月XX日 5: XX月XX日 XX时XX分XX秒 6: yyyymmddhhmmss
     */
    public static String getDate(java.util.Date date, int type) {
        if (date == null)
            return "";
        // Calendar c=Calendar.getInstance();
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(date);
        int y = c.get(Calendar.YEAR);
        int m = c.get(Calendar.MONTH) + 1;
        int d = c.get(Calendar.DAY_OF_MONTH);
        int h = c.get(Calendar.HOUR_OF_DAY);
        int mi = c.get(Calendar.MINUTE);
        int s = c.get(Calendar.SECOND);
        String str = null;
        switch (type) {
            case 1:
                str = String.valueOf(y) + "-"
                        + addStr(String.valueOf(m), "0", 2, true) + "-"
                        + addStr(String.valueOf(d), "0", 2, true);
                break;
            case 2:
                str = String.valueOf(y) + "-"
                        + addStr(String.valueOf(m), "0", 2, true) + "-"
                        + addStr(String.valueOf(d), "0", 2, true) + " "
                        + addStr(String.valueOf(h), "0", 2, true) + ":"
                        + addStr(String.valueOf(mi), "0", 2, true) + ":"
                        + addStr(String.valueOf(s), "0", 2, true);
                break;
            case 3:
                str = String.valueOf(y) + "年"
                        + addStr(String.valueOf(m), "0", 2, true) + "月"
                        + addStr(String.valueOf(d), "0", 2, true) + "日";
                break;
            case 4:
                str = addStr(String.valueOf(m), "0", 2, true) + "月"
                        + addStr(String.valueOf(d), "0", 2, true) + "日";
                break;
            case 5:
                str = addStr(String.valueOf(m), "0", 2, true) + "月"
                        + addStr(String.valueOf(d), "0", 2, true) + "日"
                        + addStr(String.valueOf(h), "0", 2, true) + "时"
                        + addStr(String.valueOf(mi), "0", 2, true) + "分"
                        + addStr(String.valueOf(s), "0", 2, true) + "秒";
                break;
            case 6:
                str = String.valueOf(y) + addStr(String.valueOf(m), "0", 2, true)
                        + addStr(String.valueOf(d), "0", 2, true)
                        + addStr(String.valueOf(h), "0", 2, true)
                        + addStr(String.valueOf(mi), "0", 2, true)
                        + addStr(String.valueOf(s), "0", 2, true);
                break;
        }
        return str;
    }

    /**
     * 获取两日期之间的天数
     *
     * @param date1
     *            日期1
     * @param date2
     *            日期2
     * @return int 前日期大于后日期的天数
     */
    public static long getDayBetween(java.util.Date date1, java.util.Date date2) {
        if (date1 == null || date2 == null)
            return 0;
        long days = (date1.getTime() - date2.getTime()) / 1000 / 60 / 60 / 24;
        return days;
    }

    /**
     * 返回指定日期的最大天数
     *
     * @param year1
     *            年份
     * @param month1
     *            月份
     * @return int 返回最大天数
     */
    public static int getDayCount(String year1, String month1) {
        int dayCount = 0;
        int month = Integer.parseInt(month1);
        int[] dayOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

        if ((checkLeapYear(year1)) && (month == 2)) {
            dayCount = 29;
        } else {
            dayCount = dayOfMonth[month - 1];
        }
        return dayCount;
    }

    /**
     * 去处科学计数法
     *
     * @param str
     *            要处理的数值
     * @param x
     *            要保留的位数
     * @return String 返回String类型，为空返回零
     */
    public static String getEToStr(float str, int x) {
        if (str == 0)
            return "0";

        String rStr = "";
        while (rStr.length() < x)
            rStr += "#";
        if (x > 0) {
            rStr = "." + rStr;
        }
        DecimalFormat df = new DecimalFormat("###########" + rStr);
        return df.format(str);
    }

    /**
     * 去处科学计数法
     *
     * @param str
     *            要处理的数值字符串
     * @param x
     *            要保留的位数
     * @return String 返回String类型，为空返回零
     */
    public static String getEToStr(String str, int x) {
        if (str == null)
            return "0";
        String rStr = "";
        while (rStr.length() < x)
            rStr += "#";
        DecimalFormat df = new DecimalFormat("###########." + rStr);
        return df.format(Double.parseDouble(str));
    }

    /**
     * 保留x位小数(不进行四舍五入)
     *
     * @param str
     *            数值字符串
     * @param x
     *            有效位数
     * @return String 处理后的数值字符串
     */
    public static String getFloor(String str, int x) {
        double dbl = Double.parseDouble(str);
        int zInt = Integer.parseInt(addStr("1", "0", x + 1, false));
        double db2 = dbl * zInt;
        dbl = java.lang.Math.floor(db2) / zInt;
        // dbl = java.lang.Math.floor(db2+0.5)/zInt;//四舍五入
        return dbl + "";
    }

    /**
     * 分页页角
     *
     * @param url
     *            访问页面
     * @param request
     * @param total
     *            总记录数
     * @return 输出字符串
     */
    public static String getFootPage(String url, HttpServletRequest request,
                                     int total) {
        StringBuffer rtn = new StringBuffer();
        // if(url.equals(""))
        url = request.getRequestURL().toString();
        int curPage = 1;
        int pageSize = 20;
        try {
            if (request.getParameter("pageSize") != null
                    && !request.getParameter("pageSize").equals("")) {
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            }
        } catch (Exception e) {
            // 传递的参数中没有pageSize
        }

        /**
         * try { pageSize = CommonUtil.getPrintProperties("pageSize",
         * "/db.properties"); } catch (Exception e) { e.printStackTrace(); }
         */
        String rpstr = "page=";
        int maxP = (int) Math.ceil(((double) total) / pageSize);

        try {
            curPage = Integer.parseInt(request.getParameter("page"));
            rpstr = rpstr + curPage;
        } catch (Exception e) {
        }
        if (curPage > maxP) {
            curPage = maxP;
        }
        if (curPage < 1) {
            curPage = 1;
        }
        String tj = CommonUtil.nullToStr(request.getQueryString());
        tj = tj.replaceAll(rpstr, "");
        tj = tj.replaceAll("&&", "&");
        if (tj.indexOf("recCount=" + total) < 0) {
            tj = tj + "&recCount=" + total;
        }
        tj = convert(tj);
        rtn.append("<div id='div1'>共 [");
        rtn.append(total);
        rtn.append(" ]条记录 ");
        rtn.append(" 每页显示[ ");
        rtn.append(pageSize);
        rtn.append(" ]条 ");
        rtn.append("共 [ ");
        rtn.append(maxP);
        rtn.append(" ]页");
        rtn.append(" 第[ ");
        rtn.append(curPage);
        rtn.append(" ] 页");
        // if(maxP>1){
        if (curPage != 1) {
            rtn.append(" <a href=" + url + "?" + tj + ">");
            rtn.append("首页");
            rtn.append("</a> ");
            rtn.append(" <a href=" + url + "?" + tj + "&page=" + (curPage - 1)
                    + ">");
            rtn.append("上一页");
            rtn.append("</a> ");
        }
        if (curPage < maxP) {
            rtn.append(" <a href=" + url + "?" + tj + "&page=" + (curPage + 1)
                    + ">");
            rtn.append("下一页");
            rtn.append("</a> ");
            rtn.append(" <a href=" + url + "?" + tj + "&page=" + (maxP) + ">");
            rtn.append("末页");
            rtn.append("</a> ");
        }
        // }

        //2008-06-17

        rtn.append("</div>");
        return rtn.toString();
    }

    /**
     * 将BASE64编码格式字符串解码
     *
     * @param str
     *            字符串
     * @return String 返回处理后的字符串
     */
    public static String getFromBASE64(String str) {
        String rtn = null;
        BASE64Decoder decoder = new BASE64Decoder();
        if (str != null) {
            try {
                byte[] b = decoder.decodeBuffer(str);
                rtn = new String(b, "GBK");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rtn;
    }

    /**
     * 功能:该方法用来分割从前台发送过来的数据流
     *
     * @param str
     * @return Map
     */
    public static Map getParameters(String str) {
        String[] str1 = str.split("&");
        Map hash = new HashMap();
        for (int i = 0; i < str1.length; i++) {
            String[] str2 = str1[i].split("=");
            if (str2.length == 1) {
                hash.put(str2[0], "");
            } else {
                hash.put(str2[0], CommonUtil.reconvert(nullToStr(str2[1])));
            }
        }
        return hash;
    }

    /**
     * 返回properties配置文件中的节
     *
     * @param key
     *            键名
     * @param fileName
     *            配置文件名
     * @return 键名对应的值,默认值为20
     */
    public static int getPrintProperties(String key, String fileName) {
        int rel = 20;
        try {
            if (Props == null) {
                Props = new Properties();
                // Props.load(CommonUtil.class.getResourceAsStream("/message.properties"));
                Props.load(CommonUtil.class.getResourceAsStream(fileName));
            }
            rel = Integer.parseInt(Props.getProperty(key));
        } catch (IOException e) {
            log.error(e.getMessage());
            rel = 20;
        }
        return rel;
    }

    /**
     * 返回properties配置文件中的节
     *
     * @param key
     *            键名
     * @param fileName
     * @return 键名对应的值
     */
    public static String getProperties(String key, String fileName) {
        String rel = "";
        try {
            if (Props == null) {
                Props = new Properties();
                // Props.load(CommonUtil.class.getResourceAsStream("/message.properties"));
                Props.load(CommonUtil.class.getResourceAsStream(fileName));
            }
            rel = Props.getProperty(key);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return rel;
    }

    /**
     * 获取发出请求文件的物理路径
     *
     * @param application
     *            application对象就是Servlet中的ServerContext
     * @param request
     *            发出请求的jsp/servlet
     * @return 返回请求文件的物理路径
     */
    public static String getRealFilePath(ServletContext application,
                                         HttpServletRequest request) {
        String strAbsPath = getRealFullFile(application, request);
        strAbsPath = new File(strAbsPath).getParent();
        return strAbsPath;
    }

    /**
     * 获取用户发出请求的完整文件名<br>
     * <b>request.getRealPath()只是取得根目录所对应的绝对路径</b>
     *
     * @param application
     *            application对象就是Servlet中的ServerContext
     * @param request
     *            发出请求的jsp/servlet
     * @return 返回包含文件物理路径的文件名
     */
    public static String getRealFullFile(ServletContext application,
                                         HttpServletRequest request) {
        String strAbsPath = "";
        strAbsPath = application.getRealPath(request.getRequestURI());
        return strAbsPath;
    }

    /**
     * ===============================日期处理结束=====================//
     * ==============================数字处理==========================//
     * 保留x位小数(将进行四舍五入)
     *
     * @param str
     *            需保留的字符串型数据
     * @param x
     *            需要保留的小数位
     * @return String 返回保留后的字符串
     */
    public static String getRound(String str, int x) {
        if (str == null || str.equals(""))
            return "0";
        String rStr = "";
        while (rStr.length() < x)
            rStr += "#";
        java.text.DecimalFormat df = new java.text.DecimalFormat("##." + rStr);
        return df.format(Double.parseDouble(str));
    }

    /**
     * 取代码的缩位值，如果代码最后两位都是零，将两个零同时去掉
     *
     * @param dm
     * @return
     */

    public static String getShortCode(String dm) {
        String tmp = dm;
        while (tmp != null && tmp.endsWith("00")) {
            tmp = tmp.substring(0, tmp.length() - 2);
        }
        return tmp;
    }

    /**
     * 将数值字符串保留x位小数转换为double型返回
     *
     * @param str
     *            要处理的数值字符串
     * @param x
     *            要保留的位数
     * @return double 返回double类型，为空返回零
     */
    public static double getStrToDouble(String str, int x) {
        if (str == null)
            return 0;
        return Double.parseDouble(getRound(str, x));
    }

    /**
     * 隐藏ip地址的最好一个点后的数字，用*好替换
     *
     * @param ipAddress
     * @return ip
     */
    public static String hideIP(String ipAddress) {
        String rtn = "";
        if (ipAddress != null) {
            if (ipAddress.lastIndexOf(".") != -1) {
                rtn = ipAddress.substring(0, ipAddress.lastIndexOf(".") + 1)
                        + "*";
            }
        }
        return rtn;
    }

    /**
     * 对串进行分解，并判断，用户系统管理的权限分配
     *
     * @param str
     * @param spStr
     * @param value
     * @return 是否应该选中，为true时选中checkbox
     */
    public static boolean isChecked(String str, String spStr, String value) {
        boolean rtnVal = false;
        String array[] = stringToArray(str, spStr);
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(value)) {
                rtnVal = true;
            }
        }
        return rtnVal;
    }

    /**
     * 将字符串中的一些特定字符转换为HTML标记
     *
     * @param str
     *            被替换的字符串
     * @return String 返回处理后的字符
     */
    public static String jspReplace(String str) {
        String strDest = "";
        strDest = replace(str, "\t", "    ");
        strDest = replace(strDest, "\r\n", "\n");
        strDest = replace(strDest, "\n", "<br>");
        strDest = replace(strDest, " ", "&nbsp;");
        return strDest;
    }

    /**
     * 将空值转换为空字符串
     *
     * @param str
     *            字符串
     * @return String 返回处理后的字符串
     */
    public static String nullToStr(String str) {
        return str == null || str.equals("null") ? "" : str.trim();
    }

    /**
     * 解析format格式的日期 date
     *
     * @param date
     * @param format
     * @return 解析后的日期
     */
    public static Date parseDate(String date, String format) {
        if (date == null || date.equals("")) {
            return null;
        }
        if (format == null || format.trim().equals("")) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date rtnDate = null;
        try {
            rtnDate = sdf.parse(date);
        } catch (ParseException e) {
            log.info("parseDate:" + date + "不能被正确解析");
        }
        return rtnDate;

    }

    /**
     * ===============================数字处理结束=====================//
     */

    /**
     * 将s转换为float
     *
     * @param s
     * @return s的float值
     */
    public static float parseFloat(String s) {
        float rtnVal = 0;
        try {
            rtnVal = Float.parseFloat(s);
        } catch (NumberFormatException e) {
            log.info(e);
        }
        return rtnVal;
    }

    /**
     * 将ibatis生成的记录集合对应的XML字符串解析为Map对象
     *
     * @param xml
     *            要解析的xml字符串
     * @return 数据记录集合 名值对(字段名和字段值)
     */
    public static List parseXMLtoMap(StringBuffer xml) {
        List list = new ArrayList();
        if (xml == null || xml.length() <= 0) {
            return list;
        }
        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder dombuilder = domfac.newDocumentBuilder();
            Document doc = dombuilder.parse(new ByteArrayInputStream(xml
                    .toString().getBytes()));
            NodeList records = doc.getElementsByTagName("RECORD");
            Node node = null;
            NodeList field_node = null;
            for (int i = 0; i < records.getLength(); i++) {
                field_node = records.item(i).getChildNodes();
                Map map = new HashMap();
                for (int j = 0; j < field_node.getLength(); j++) {
                    node = field_node.item(j);
                    if (node == null)
                        continue;
                    String key = node.getNodeName();
                    String field = "";
                    if (node.getFirstChild() != null)
                        field = node.getFirstChild().toString();
                    if (key != null && !key.equals("#text")) {
                        if (field != null) {
                            if (field.split("#text:").length >= 2)
                                field = field.split("#text:")[1];
                            else
                                field = "";
                            if (field.lastIndexOf("]") != -1) {
                                field = field.split("]")[0];
                            }
                        }
                        map.put(key.trim(), field.trim());
                    }
                }
                list.add(map);
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 字符串编码反转换为ISO8859_1
     *
     * @param str
     *            被处理的字符串
     * @return String 将jsp提交的数据进行转换放入数据库中
     */
    public static String reconvert(String str) {
        return str;
		/*
		 * String str1 = null; if (str != null) { try { str1 = new
		 * String(str.getBytes("GBK"), "ISO8859_1"); } catch (Exception e) {
		 * return str1; } } return str1;
		 */
    }

    /**
     * ================================字符串处理======================//
     * 将字符串中的一些特定字符转换为HTML标记
     *
     * @param str
     *            被替换的字符串
     * @return String 返回处理后的字符
     */
    public static String replace(String str) {
        String strDest = "";
        strDest = replace(str, "&", "&amp;");
        strDest = replace(strDest, "<", "&lt;");
        strDest = replace(strDest, ">", "&gt;");
        strDest = replace(strDest, "\t", "    ");
        strDest = replace(strDest, "\r\n", "\n");
        strDest = replace(strDest, "\n", "<br>");
        strDest = replace(strDest, "  ", "&nbsp;");
        strDest = replace(strDest, "<", "&lt;");
        strDest = replace(strDest, ">", "&gt;");
        strDest = replace(strDest, "null", " ");
        return strDest;
    }

    /**
     * 字符替换
     *
     * @param rStr
     *            被替换的字符串
     * @param rFix
     *            被替代的字符串
     * @param rRep
     *            替代的字符串
     * @return String 将字符串rStr中的字符串rFix替换成rRep
     */
    public static String replace(String rStr, String rFix, String rRep) {
        int idx1 = 0;
        int idx2 = rStr.indexOf(rFix, idx1);
        int len = rFix.length();
        StringBuffer sb = new StringBuffer();
        while (true) {
            if (idx2 == -1) {
                sb.append(rStr.substring(idx1, rStr.length()));
                break;
            }
            sb.append(rStr.substring(idx1, idx2));
            sb.append(rRep);
            idx1 = idx2 + len;
            idx2 = rStr.indexOf(rFix, idx1);
        }
        String gRtnStr = sb.toString();
        return gRtnStr;
    }

    /**
     * ================================字符串处理======================//
     * 将字符串中的一些特定字符转换为xml标记 ,针对XML转换
     *
     * @param str
     *            被替换的字符串
     * @return String 返回处理后的字符
     */
    public static String replaceNull(String str) {
        String strDest = "";
        strDest = replace(str, "&", "");
        strDest = replace(strDest, "<", "&lt;");
        strDest = replace(strDest, ">", "&gt;");
        strDest = replace(strDest, "\t", "    ");
        strDest = replace(strDest, "\r\n", "\n");
        strDest = replace(strDest, "\n", "\n");
        strDest = replace(strDest, "&nbsp;", " ");
        strDest = replace(strDest, "</br>", "\n");
        strDest = replace(strDest, "null", " ");
        return strDest;
    }

    /**
     * 将字符串由x编码转换为s编码
     *
     * @param str
     *            被替换的字符串
     * @param x
     *            字符编码类型
     * @param s
     *            字符编码类型
     * @return String 字符串编码转换x-->s
     */
    public static String setEncode(String str, String x, String s) {
        if (str == null)
            return "";
        String returnStr = null;
        try {
            returnStr = new String(str.getBytes(x), s);
        } catch (Exception e) {
        }
        return returnStr;
    }

    /**
     * 把字符串按给定字符串分解成字符数组
     *
     * @param str
     *            要转换的字符串
     * @param spStr
     *            分割字符串
     * @return 返回字符数组
     */
    public static String[] stringToArray(String str, String spStr) {
        if (str == null)
            return null;
        try {
            StringTokenizer st = new StringTokenizer(str, spStr);
            String strArray[] = new String[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                strArray[i] = st.nextToken();
                i++;
            }
            return strArray;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 将字符串按给定字符分解
     *
     * @param str
     *            要转换的字符串
     * @param chr
     *            分割字符
     * @param type
     *            分割方法 0:最前和最后分割符不会加入数组
     * @return Object[] 对象数组
     */
    public static Object[] strToArr(String str, String chr, int type) {
        if (str == null || str.length() == 0)
            return null;
        // 计算出数组长度count 并计算出每个分割符的位置，把值放入Vector变量indexSort中
        // int count = 0;
        int index = 0;
        int oldIndex = 0;
        int lens = str.length();
        int len = chr.length();
        Vector indexSort = new Vector();
        try {
            if (type == 0) {
                while (true) {
                    index = str.indexOf(chr, oldIndex);
                    if (index != -1) {
                        if (index > 0) {
                            indexSort
                                    .addElement(str.substring(oldIndex, index));
                        }
                        oldIndex = index + len + 0;
                    } else {
                        if (oldIndex < lens) {
                            indexSort.addElement(str.substring(oldIndex, lens));
                        }
                        break;
                    }
                }
            } else {
                while (true) {
                    index = str.indexOf(chr, oldIndex);
                    if (index != -1) {
                        indexSort.addElement(str.substring(oldIndex, index));
                        oldIndex = index + len + 0;
                    } else {
                        if (oldIndex <= lens) {
                            indexSort.addElement(str.substring(oldIndex, lens));
                        }
                        break;
                    }
                }
            }
        } catch (NullPointerException e) {
            return null;
        }
        return indexSort.toArray();
    }

    /**
     * 截取字符串方法
     *
     * @param str
     * @param split
     *            分隔符一
     * @param split1
     *            分隔符二
     * @return 截取后的字符串
     */
    public static String subStr(String str, String split, String split1) {
        if (str == null)
            return null;
        if (str.indexOf(split) != -1) {
            return str.substring(str.indexOf(split) + 1, str.indexOf(split1,
                    str.indexOf(split)));
        } else {
            return "";
        }
    }
    /**
     * @param table_name
     *            表名称
     * @param list
     *            数据列表
     * @param dm
     *            代码字段
     * @param mc
     *            名称字段
     * @return
     */
    public static String toDmJsStr(String table_name, List list, String dm,
                                   String mc) {
        return toDmJsStr(table_name, list, dm, mc, "", "");
    }
    /**
     * @param table_name
     *            表名称
     * @param list
     *            数据列表
     * @param dm
     *            代码字段
     * @param mc
     *            名称字段
     * @param xztj
     *            限制条件字段
     * @return
     */
    public static String toDmJsStr(String table_name, List list, String dm,
                                   String mc, String xztj) {
        return toDmJsStr(table_name, list, dm, mc, xztj, "");
    }

    /**
     * @param table_name
     *            表名称
     * @param list
     *            数据列表
     * @param dm
     *            代码字段
     * @param mc
     *            名称字段
     * @param xztj
     *            限制条件字段
     * @return
     */
    public static String toDmJsStr(String table_name, List list, String dm,
                                   String mc, String xztj, String mcpyt)  {
        Map hash1 = null;
        StringBuffer pyt = new StringBuffer("var " + table_name
                + " =new Array();\n");
        if (list == null) {
            return pyt.toString();
        }
        int len = list.size();

        for (int i = 0; i < len; i++) {
            hash1 = (HashMap) list.get(i);
            String pyt_dm=String.valueOf(hash1.get(dm));
            String pyt_mc=String.valueOf(hash1.get(mc));
            pyt.append(""+table_name+"["+i+"]=new  Array('"+pyt_dm.trim()+ "',");
            pyt.append("'").append(pyt_mc.trim()).append("',");
            pyt.append("'").append((mcpyt.equals("")|| hash1.get(mcpyt) == "") ? GetCh2Spell
                    .getFirstSpell(String.valueOf(hash1.get(mc))) : hash1.get(mcpyt)).append("',");
            pyt.append("'").append(xztj.equals("") ? "" : hash1.get(xztj)).append("'").append(");\n");
            hash1 = null;
        }
        return pyt.toString();
    }


    /**
     * @param table_name
     *            表名称
     * @param list
     *            数据列表
     * @param dm
     *            代码字段
     * @param sjDm 上级代码字段
     * @param mc
     *            名称字段
     * @return
     */
    public static String toDTreeJsStr(String table_name, List list, String dm,String sjDm,
                                      String mc){
        return toDTreeJsStr(table_name,list,dm,sjDm,mc,"false");
    }
    /**
     * @param table_name
     *            表名称
     * @param list
     *            数据列表
     * @param dm
     *            代码字段
     * @param sjDm 上级代码字段
     * @param mc
     *            名称字段
     * @param isMultiple 是否多选
     * @return
     */
    public static String toDTreeJsStr(String table_name, List list, String dm,String sjDm,
                                      String mc,String isMultiple) {

        return CommonUtil.toDTreeJsStr(table_name, list, dm, sjDm, mc, isMultiple, false);
    }

    /**
     * @param table_name
     *            表名称
     * @param list
     *            数据列表
     * @param dm
     *            代码字段
     * @param sjDm 上级代码字段
     * @param mc
     *            名称字段
     * @param isMultiple 是否多选
     * @param isChildrenSelected isMultiple=‘true’时有效，是否同时选中下级
     * @return
     */
    public static String toDTreeJsStr(String table_name, List list, String dm,String sjDm,
                                      String mc,String isMultiple,boolean isChildrenSelected) {
        Map hash1 = null;
        StringBuffer pyt = new StringBuffer("<script src='/inc/platform/js/dtree.js'></script>\n");
        pyt.append("<link rel='StyleSheet' href='/public/css/dtree.css' type='text/css' />\n");
        pyt.append("<div id='Layer1' class='dtree'></div>\n");
        pyt.append("<script>\n");
        pyt.append("function Choose(dm,mc){");
        pyt.append("parent.setVal(dm,mc);");
        pyt.append("}\n");
        pyt.append("var d = new dTree('d');\n");
        if(isMultiple!=null&&isMultiple.equals("true")){
            pyt.append("d.config.isMultiple=true;");
            if(isChildrenSelected){
                pyt.append("d.config.isChildrenSelected=true;");
            }
            pyt.append("d.config.dmFiled='dm';");
            pyt.append("d.config.mcFiled='mc';");
        }
        if (list == null||list.size()==0) {
            pyt.append("</script>");
            return pyt.toString();
        }
        int len = list.size();
        List listSj = new ArrayList();
        hash1 = (HashMap) list.get(0);
        //if(len==1){
        pyt.append("d.add('ffff',-1,'请选择');\n");
        //}else{
        //	pyt.append("d.add('"+hash1.get(dm)+"','-1','"+hash1.get(mc)+"');\n");

        //}
        for (int i = 0; i < len; i++) {
            hash1 = (HashMap) list.get(i);
            if(hash1.get(sjDm)!=null&&listSj.indexOf(hash1.get(sjDm).toString())!=-1){
                //pyt.append("d.add('"+hash1.get(dm)+"','ffff','"+hash1.get(mc)+"');\n");
                pyt.append("d.add('").append(hash1.get(dm)).append("','").append(hash1.get(sjDm)).append("','").append(hash1.get(mc)).append("');\n");
            }else{
                pyt.append("d.add('").append(hash1.get(dm)).append("','ffff','").append(hash1.get(mc)).append("');\n");
            }
            listSj.add(hash1.get(dm).toString());
            hash1 = null;
        }
        pyt.append("	var str = '';\n");
        pyt.append("if (document.getElementById) {\n");
        pyt.append("   str += d.addNode(d.root);\n");
        pyt.append("}else{\n");
        pyt.append("   str += 'Browser not supported.';\n");
        pyt.append("}\n");
        pyt.append("   d.completed = true;\n");
        pyt.append("   document.getElementById('Layer1').innerHTML=str;\n");
        //默认已选为第0个
        pyt.append("   curindex=0;\n");
        //pyt.append("   disp(0);\n");

        //pyt.append("alert(d);");
        pyt.append("</script>");


        return pyt.toString();
    }

    /**
     * 将字符串以十六进制表示返回
     *
     * @param s
     *            要转换的字符串
     * @return String 十六进制字符串
     */
    public static String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = "0000" + Integer.toHexString(ch);
            str = str + s4.substring(s4.length() - 4) + "";
        }
        return str;
    }

    /**
     * 将map内容导出为json串
     *
     * @param map
     * @param jsonName
     * @return
     */
    private static String toJSON(Map map, String jsonName) {
        if (jsonName == null) {
            return "";
        }
        if (map == null) {
            return jsonName + "={}\n";
        }
        Iterator iterator = map.keySet().iterator();
        StringBuffer srcBuffer = new StringBuffer();
        String key = null;
        srcBuffer.append(jsonName);
        srcBuffer.append("={\n");
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            srcBuffer.append(key.toLowerCase());
            srcBuffer.append(":'");
            srcBuffer.append(CommonUtil.convert(
                    CommonUtil.nullToStr(String.valueOf(map.get(key))))
                    .replaceAll("'", "\""));
            if (iterator.hasNext())
                srcBuffer.append("',\n");
        }
        srcBuffer.append("'\n}\n");
        return srcBuffer.toString();
    }

    /**
     * 将list内容转换为json串。
     * @param jsonName
     * @param list
     * @return
     */
    public static String toJSON(String jsonName, List list) {
        if (list == null) {
            return "var " + jsonName + "=new Array();\n";
        }
        StringBuffer srcBuffer = new StringBuffer();
        srcBuffer.append("var " ).append(jsonName).append( "= new Array();\n");
        for (int i = 0, len = list.size(); i < len; i++) {
            srcBuffer.append(toJSON((Map) list.get(i), jsonName + "[" + i + "]"));
        }
        return srcBuffer.toString();
    }

    /**
     * 计算合计 如果role中的第一条元素为rowTotal则进行行合计
     *
     * @param list
     * @param role
     * @return 带合计的列表
     */
    public static List total(List list, List role) {
        List roleTmp = new ArrayList(role);
        Iterator iterator = list.iterator();
        Iterator keys;
        Map map;
        Map total = new HashMap();
        String key = "";
        Object value = "";
        BigDecimal d;
        BigDecimal rowTotal = new BigDecimal(0);
        boolean isRowTotal = false;// 是否进行行合计
        boolean isCalculate = false;// 是否进行相关计算
        if (roleTmp != null && !roleTmp.isEmpty()) {

            if (roleTmp.get(0) instanceof String
                    && roleTmp.get(0).equals("rowTotal")) {
                roleTmp.remove(0);
                isRowTotal = true;
            }
            if (!roleTmp.isEmpty()) {
                isCalculate = true;
            }
        }
        if (list == null || list.isEmpty())
            return list;
        map = (Map) list.get(list.size() - 1);
        if (map.containsKey("autototaled"))
            return list;
        while (iterator.hasNext()) {
            map = (Map) iterator.next();
            if (isCalculate)
                map = calculate(map, roleTmp);
            if (isRowTotal)
                rowTotal = new BigDecimal(0);
            keys = map.keySet().iterator();
            while (keys.hasNext()) {
                key = (String) keys.next();
                value = map.get(key);
                if (value instanceof Number) {
                    if (isRowTotal) {
                        rowTotal = rowTotal.add((BigDecimal) value);
                    }
                    d = (BigDecimal) value;
                    if (total.containsKey(key)) {
                        BigDecimal tmp = (BigDecimal) total.get(key);
                        total.put(key, tmp.add(d));
                    } else {
                        total.put(key, d);
                    }
                } else {
                    if (!total.containsKey(key)) {
                        if (map.get(key) != null
                                && !map.get(key).equals("null"))
                            total.put(key, "--");
                    }
                }
            }
            if (isRowTotal) {
                map.put("rowTotal", rowTotal);
                BigDecimal tmp = (BigDecimal) total.get("rowTotal");
                if (tmp != null) {
                    total.put("rowTotal", tmp.add(rowTotal));
                } else {
                    total.put("rowTotal", rowTotal);
                }
            }
        }
        if (!total.isEmpty()) {
            if (roleTmp != null && !roleTmp.isEmpty())
                total = calculate(total, roleTmp);

            total.put("autototaled", "1");
            list.add(total);
        }
        return list;
    }

    /**
     * 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.
     *
     * @param s
     *            原文件名
     * @return 重新编码后的文件名
     */
    public static String toUtf8String(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception ex) {
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 通过list来转换数据为xml
     *
     * @param list
     * @param par
     * @param author
     * @return xml文件
     */
    public static String toXML(List list, String par, String author) {
        String rtn = "";
        Map map = new HashMap();
        StringBuffer str = new StringBuffer("");
        if (list != null && !list.isEmpty()) {

            Iterator it = list.iterator();
            // str.append("<?xml version=\"1.0\" encoding=\"GB2312\"?>\n");
            str.append("<" ).append( par.toUpperCase() ).append( ">");
            str.append("<AUTHOR>");
            str.append(author);
            str.append("</AUTHOR>");
            str.append("<CREATE_TIME>");
            str.append(getCurrentDate());
            str.append("</CREATE_TIME>");
            while (it.hasNext()) {
                map = (Map) it.next();
                str.append(toXML(map, par));
            }

            str.append("</" ).append( par.toUpperCase() ).append( ">");
        }
        rtn = str.toString();
        return rtn;
    }

    /**
     * 通过map来生成xml
     *
     * @param map
     *            需转换的map
     * @param par
     *            参数
     * @return xml串
     */
    public static String toXML(Map map, String par) {

        String rtn = "";
        StringBuffer str = new StringBuffer("");
        String tmp = "";
        Iterator it = map.keySet().iterator();
        if (map != null && !map.isEmpty()) {
            str.append("<RECORD>");
            while (it.hasNext()) {
                tmp = (String) it.next();
                str.append("<" ).append( tmp ).append( ">");
                str.append(""
                ).append( convert(String.valueOf(map.get(tmp) == null ? ""
                        : String.valueOf(map.get(tmp))).replaceAll("&nbsp;", "")) ).append( "");
                str.append("</" ).append( tmp ).append( ">");
            }
            str.append("</RECORD>");
        }
        rtn = str.toString();

        return rtn;

    }

    /**
     * @param str
     * @return String
     */
    public static String YESORNO(String str) {
        String str1 = "";
        if (str == null || str.equals("")) {
            str1 = "";
        } else {
            if (str.equals("Y"))
                str1 = "是";
            else
                str1 = "否";
        }
        return str1;
    }

    /**
     * 将str字符串自动左补指定字符到指定长度
     * @param str:主字符串   s：指定字符串   len：指定长度
     * @return String
     */
    public static String LPAD(String str,String s,int len) {
        String str1 = "";
        if(str.length()<len)
        {
            for(int m=0;m<len-str.length();m++)
            {
                str1=str1+s;
            }
        }
        return str1+str;
    }

    public static Map getMapByKeyValue(List list ,String key,String vlaue){
        for(int i = 0;i<list.size();i++){
            Map map = (Map)list.get(i);
            if(vlaue.equals(map.get(key))){
                return map;
            }
        }
        return null;
    }

    /**
     *
     * 获取编号顺序号
     * @param     index:上一个编号
     * @return String
     */
    public static String getKey(String index){
        String lstmp="",lsret="",asmax="";
        int nums,j,i;
        String[]sw={"0","1","2","3","4","5","6","7","8","9" };
        asmax=index;
        if(asmax==null)
            asmax="0000";
        nums=asmax.length();
        boolean stepOut=false;
        for(j=nums-1;j>=0;j--){
            if(stepOut) break;
            lstmp=asmax.substring(j,j+1);
            for(i=0;i<sw.length;i++){
                if(lstmp.equals(sw[i])){
                    if(i==sw.length-1){
                        lstmp="0";
                        lsret=lstmp+lsret;
                    }else{
                        lstmp=sw[i+1];
                        lsret=lstmp+lsret;
                        stepOut=true;
                    }
                    break;
                }
            }
        }
        lsret=asmax.substring(0,asmax.length()-lsret.length())+lsret;
        return lsret;
    }
}
